<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" @click="addRoleFn" @close="closeDialog">新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="roleList">
              <el-table-column type="index" label="序号" width="120" :index="indexMethod" />
              <el-table-column prop="name" label="角色名称" width="200" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="showAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)" @close="closeDialog">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)" @close="closeDialog">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- current-page 表示的当前是那一页 -->
            <!-- page-sizes 动态设置页容量的下拉列表 -->
            <!-- page-size 表示当前的页容量 -->
            <!-- layout 表示的分页样式 -->
            <!-- total 表示的 一共有多少条 -->
            <!-- @current-change 表示的点击页码的时候执行的事件-->
            <!-- @size-change 表示的动态设置页容量的时候执行的事件 -->
            <el-pagination

              :current-page="page"

              :page-sizes="[4,20,30,40]"

              :page-size="pagesize"

              layout="total,sizes,prev,pager,next,jumper"

              :total="total"

              @current-change="handleCurrentChange"

              @size-change="handleSizeChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="showTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" :close-on-click-modal="false" @close="closeAssignDialog" @open="dialogOpenFn">
        <!-- show-checkbox 表示节点是否可以被选择 -->
        <!-- check-strictly 父子节点不关联 -->
        <!-- default-expand-all 是否默认展开 -->
        <el-tree ref="tree" v-loading="isTreeLoading" :data="permissionList" :props="{ label: 'name' }" default-expand-all check-strictly show-checkbox node-key="id" />
        <template #footer>
          <div style="text-align: right">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="assignPerm">确认</el-button>

          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import { getRoleListApi,
  delRoleApi,
  addRoleApi,
  getEditRoleApi,
  editRoleApi,
  getCompanyInfoApi,
  assignPermApi
} from '@/api/setting'
import { mapGetters } from 'vuex'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      loading: false,
      roleList: [],
      page: 1, // 当前页
      pagesize: 4, // 每页条数
      total: 0, // 总条数
      showDialog: false,
      roleId: '',
      showAssignDialog: false,
      permissionList: [],
      isTreeLoading: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    },
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo() // 获取公司信息
  },
  methods: {
    // 点击确认
    async assignPerm() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPermApi({ id: this.roleId, permIds })
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    },
    //
    async  dialogOpenFn() {
      this.isTreeLoading = true
      await this.getPermissionList()
      await this.getPermissionDetailFn()
      this.isTreeLoading = false
    },
    // 数据回显
    async getPermissionDetailFn() {
      const { data: { permIds }} = await getEditRoleApi(this.roleId)
      // 回显
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 获取权限
    async getPermissionList() {
      const { data } = await getPermissionListApi()
      this.permissionList = transListToTreeData(data, '0')
    },
    // 打开配置权限弹框
    showAssign(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getRoleList() {
      this.loading = true
      const { data } = await getRoleListApi(this.page, this.pagesize)
      // console.log(data)
      this.roleList = data.rows
      this.total = data.total
      this.loading = false
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    /**
* 点击页码
*/
    handleCurrentChange(val) {
      // console.log(val)
      this.page = val
      this.getRoleList()
    },
    /**
* 修改页容量
*/
    handleSizeChange(val) {
      // console.log(val)
      this.pagesize = val
      this.getRoleList()
    },
    // 删除
    del(id) {
      // console.log(id)
      this.$confirm('你确认要进行删除么?', '温馨提示').then(async() => {
        // 删除操作成功
        await delRoleApi(id)
        if (this.roleList.length === 1 && this.page > 1) {
          this.page--
        }
        // 添加提示
        this.$message.success('删除角色成功')
        this.getRoleList()
      }).catch((error) => { console.log(error) })
    },
    // 增加、修改
    confirmAddRole() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('恭喜！修改成功')
        } else {
          await addRoleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        // this.$message.success('操作成功')
        this.getRoleList()
        this.closeDialog()
      })
    },
    addRoleFn() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      // 清空的是 绑定了prop的表单域的状态和数据
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    async edit(id) {
      // console.log(id)
      // 获取该条数据并数据回显
      const { data } = await getEditRoleApi(id)
      // console.log(data)
      this.addRoleFn()
      this.form = data
    },
    async getCompanyInfo() {
      const { data } = await getCompanyInfoApi(this.companyId)
      this.companyForm = data
    }
  }
}
</script>
